import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;

public class DragAndDropBetweenComponents {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Drag and Drop Between Components");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel sourceLabel = new JLabel("Drag me!");
        JTextField targetTextField = new JTextField();

        // 为源组件和目标组件设置TransferHandler
        sourceLabel.setTransferHandler(new TextTransferHandler());
        targetTextField.setTransferHandler(new TextTransferHandler());
        sourceLabel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                JComponent c = (JComponent) e.getSource();
                TransferHandler handler = c.getTransferHandler();
                handler.exportAsDrag(c, e, TransferHandler.COPY);
            }
        });

        frame.setLayout(new VerticalLayout());
        frame.add(sourceLabel);
        frame.add(targetTextField);

        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    // 自定义TransferHandler用于处理拖放文本
    static class TextTransferHandler extends TransferHandler {
        @Override
        public int getSourceActions(JComponent c) {
            return TransferHandler.COPY;
        }

        @Override
        protected Transferable createTransferable(JComponent c) {
            JLabel sourceLabel = (JLabel) c;
            return new StringSelection(sourceLabel.getText());
        }

        @Override
        public boolean canImport(TransferHandler.TransferSupport support) {
            return support.isDataFlavorSupported(DataFlavor.stringFlavor);
        }

        @Override
        public boolean importData(TransferHandler.TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }

            JTextField targetTextField = (JTextField) support.getComponent();

            try {
                String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                targetTextField.setText(data);
                return true;
            } catch (UnsupportedFlavorException | IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }
}